package cn.gov.anhai.utils;

import cn.gov.anhai.config.TencentConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 微信小程序工具
 */
@Component
public class WeiXinUtil {
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String GET_USER_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String POST_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Resource
    TencentConfig tencentConfig;

    public static String accessToken = null;
    public static Date accessTokenDate = null;

    public String getAccessToken() {
        if (accessToken != null && accessTokenDate != null) {
            long oldTime = accessTokenDate.getTime() + 7000 * 100;
            long newTime = new Date().getTime();
            if (oldTime > newTime) {
                return accessToken;
            }
        }
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "client_credential"));
        params.add(new BasicNameValuePair("appid", tencentConfig.getAppId()));
        params.add(new BasicNameValuePair("secret", tencentConfig.getAppSecret()));

        String html = HttpClientUtil.get(GET_ACCESS_TOKEN_URL, params);

        JSONObject jsonObject = JSONUtil.parseObj(html);
        if (!jsonObject.containsKey("access_token")) return null;

        String access_token = jsonObject.getStr("access_token");
        Integer expires_in = jsonObject.getInt("expires_in");
        accessToken = access_token;
        accessTokenDate = new Date();

        return accessToken;
    }

    public String getUserID(String code) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "authorization_code"));
        params.add(new BasicNameValuePair("appid", tencentConfig.getAppId()));
        params.add(new BasicNameValuePair("secret", tencentConfig.getAppSecret()));
        params.add(new BasicNameValuePair("js_code", code));

        String html = HttpClientUtil.get(GET_USER_ID_URL, params);

        JSONObject jsonObject = JSONUtil.parseObj(html);
        if (!jsonObject.containsKey("openid")) return null;

        String openid = jsonObject.getStr("openid");
        return openid;
    }

    public String getUserPhone(String code) {
        JSONObject data = new JSONObject();
        data.set("code", code);
        String url = POST_USER_PHONE_URL + getAccessToken();
        String html = HttpClientUtil.post(url, data.toString());

        JSONObject jsonObject = JSONUtil.parseObj(html);
        Integer errcode = jsonObject.getInt("errcode");
        //String errmsg = jsonObject.getStr("errmsg");
        if (errcode != 0) {
            return null;
        }
        JSONObject phone_info = jsonObject.getJSONObject("phone_info");
        String purePhoneNumber = phone_info.getStr("purePhoneNumber");
        return purePhoneNumber;
    }
}
